package de.hmm.hwip.connection.service;

import org.json.JSONException;
import org.json.JSONObject;
import org.osgi.framework.BundleContext;
import org.osgi.framework.ServiceReference;
import org.osgi.util.tracker.ServiceTracker;
import org.osgi.util.tracker.ServiceTrackerCustomizer;

import android.content.Context;
import android.content.SharedPreferences;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.text.format.Formatter;
import android.util.Log;
import de.hmm.hwip.connection.output.OutConThread;
import de.hmm.hwip.general.IAndroidContext;
import de.hmm.hwip.messagehandler.api.IMessageHandler;

/**
 * Configuration service for Connections
 * Waits for servicetracker and configures system
 * 
 * @author johannes mendel
 * @version 24.10.2012
 *
 */
public class ConfigurationThread implements Runnable{

	/**
	 * Class identifier to debug
	 */
	private String TAG = "Con.-Serv. Config Thread";	
	
	/**
	 * Android Context service tracker
	 */
	private ServiceTracker contextServiceTracker;
	
	/**
	 * service for Android App Context
	 */
	private IAndroidContext androidContextService;
	
    /**
     * service tracker to get the message handler service.
     */
	private ServiceTracker serviceTracker;
	
	/**
	 * message handler service
	 */
	private IMessageHandler messageService;
	
	/**
	 * OSGi bundle context
	 */
	private BundleContext bunContext;

	/**
	 * Class constructor
	 * @param context -> OSGi BundleContext
	 */
	public ConfigurationThread(BundleContext context){
		bunContext = context;
	}
	
	@Override
	public void run() {
		// getting the android context service
        contextServiceTracker = new ServiceTracker(bunContext, IAndroidContext.class.getName(), null );
        contextServiceTracker.open();
		
    // getting message handler service via service tracker and route it to messageService
		serviceTracker = new ServiceTracker(bunContext, IMessageHandler.class.getName(), new MessageTrackerCustom());
		serviceTracker.open();
		//messageService = (IMessageHandler) serviceTracker.getService();
        
		synchronized(this){
			try {
				wait(10000);
			} catch (InterruptedException e) {
				Log.e(TAG, "wait exception (start): " + e.getMessage());
			}
			
			while(true){
		        androidContextService = (IAndroidContext) contextServiceTracker.getService();
		        if(androidContextService != null){
		        	Context androidContext = androidContextService.transferContext();
		        	SharedPreferences prefs = androidContext.getSharedPreferences("hwip", 0);
		        	String gateWay = prefs.getString("gatewayip", null);
					boolean isGate = prefs.getBoolean("isgateway", false);
					boolean regFinised = prefs.getBoolean("regfinished", false);
					
					if(!(isGate) && (gateWay == null || !regFinised)){
						Log.i(TAG, "Spot is no Gateway ... search for Gateway");
						searchGateway(androidContext, gateWay);
					}else if(isGate && gateWay == null){
						Log.i(TAG, "Spot is Gateway ... add to database");
						while(true){
							if(messageService != null){
								JSONObject json = new JSONObject();
								try {
									json.put("command", "newgateway");
									json.put("service", "hwip.processing.Spot");
								} catch (JSONException e) {
									Log.e(TAG, "JSON exception: " + e.getMessage());
								}
								messageService.startAction("hwip.processing.Spot", bunContext, json, null, false);
								break;
							}else
								Log.w(TAG, "messageService is null");
							
							try{
							wait(5000);
							} catch (InterruptedException e) {
								Log.e(TAG, "wait exception (messageService): " + e.getMessage());
							}
						}
					}
					break;
		        }else{
		        	Log.w(TAG, "no android context received ... wait 5 seconds");
		        }
		        
		        try {
		        	wait(5000);
		        } catch (InterruptedException e) {
		        	Log.e(TAG, "wait exception (androidService): " + e.getMessage());
		        }
			}
		}
	}
	
	/** Servicetracker for Storage Service **
	 * if dbService is coming online tracker will notice and send Applicationcontext */

	private class MessageTrackerCustom implements ServiceTrackerCustomizer{

		@Override
		public Object addingService(final ServiceReference reference) {
			Log.i(TAG, "---------> Message Service is connected <---------");
			messageService = (IMessageHandler) bunContext.getService(reference);
			return messageService;
		}
		
		@Override
		public void modifiedService(ServiceReference arg0, Object arg1) {
			// nothing to do
			
		}

		@Override
		public void removedService(ServiceReference arg0, Object arg1) {
			messageService = null;
			
		}
		
	}
	
	/**
	 * Method to search for Gateway
	 * @param andCont - android Context
	 */
	public void searchGateway(Context andCont, String target){

		WifiManager wifiManager = (WifiManager)andCont.getSystemService(Context.WIFI_SERVICE);
		WifiInfo connectionInfo = wifiManager.getConnectionInfo();
		int tempAdress = connectionInfo.getIpAddress();
		String ipAdress = Formatter.formatIpAddress(tempAdress);
		
		JSONObject data = new JSONObject();
		try {
			data.put("service", "hwip.processing.Spot");
			data.put("command", "existspot");
			data.put("param", "ip");
			data.put("value", ipAdress);
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		OutConThread oct = new OutConThread(data, bunContext, target);
		Thread toct = new Thread(oct);
		toct.start();
	}

}
